package io.basic.char_;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

import static java.lang.System.in;

public class FileReader_ {
    /**
     * 按一个字符读取
     */
    @Test
    public void test1() {
        String filePath = "/Users/tomdayu/home/hello.txt";
        int readData = 0;
        FileReader reader = null;
        try {
            //创建流对象，用于读取文件
            reader = new FileReader(filePath);
            //从流中读取一个字符
            while ((readData = reader.read()) != -1) {
                System.out.println((char)readData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 优化速率 一次读多个字节
     */
    @Test
    public void readFile02() {
        String filePath = "/Users/tomdayu/home/hello.txt";
        int readLen = 0;
        char[] buf = new char[14];
        FileReader in = null;
        try {
            //创建流对象，用于读取文件
            in = new FileReader(filePath);
            //从流中读取多个字节到字节数组buf
            //返回实际读取的字节数
            while ((readLen = in.read(buf)) != -1) {
                System.out.println(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
